from PySide6.QtWidgets import QWidget, QVBoxLayout, QFormLayout, QDateEdit, QComboBox, QListWidget, QPushButton, QStatusBar, QCheckBox, QButtonGroup, QLabel
from PySide6.QtCore import Qt, QDate
from PySide6 import QtCore
from PySide6.QtWidgets import QCompleter

class QueryTab(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()

        # 条件输入区
        self.date_edit = QDateEdit(calendarPopup=True)
        self.date_edit.setDate(QDate.currentDate())

        self.from_station = QComboBox()
        self.from_station.setEditable(True)
        self.from_completer = QCompleter()
        self.from_completer.setCompletionMode(QCompleter.PopupCompletion)
        self.from_completer.setFilterMode(Qt.MatchContains)
        self.from_station.setCompleter(self.from_completer)

        self.to_station = QComboBox()
        self.to_station.setEditable(True)
        self.to_completer = QCompleter()
        self.to_completer.setCompletionMode(QCompleter.PopupCompletion)
        self.to_completer.setFilterMode(Qt.MatchContains)
        self.to_station.setCompleter(self.to_completer)

        # 车次类型复选组
        self.train_type_group = QButtonGroup(self)
        self.train_type_group.setExclusive(False)
        self.gaotie_btn = QCheckBox("高铁")
        self.dongche_btn = QCheckBox("动车")
        self.zhida_btn = QCheckBox("直达")
        self.train_type_group.addButton(self.gaotie_btn)
        self.train_type_group.addButton(self.dongche_btn)
        self.train_type_group.addButton(self.zhida_btn)

        # 智能推荐列表
        self.recommend_list = QListWidget()
        self.recommend_list.itemClicked.connect(self.select_recommend)

        # 控制按钮
        self.start_btn = QPushButton("开始监控")
        self.stop_btn = QPushButton("停止监控")
        self.stop_btn.setEnabled(False)

        # 实时状态显示
        self.status_bar = QStatusBar()
        self.status_bar.showMessage("就绪")

        # 表单布局
        form_layout = QFormLayout()
        form_layout.addRow("出发日期:", self.date_edit)
        form_layout.addRow("出发站:", self.from_station)
        form_layout.addRow("到达站:", self.to_station)
        form_layout.addRow("车次类型:", self.gaotie_btn)
        form_layout.addRow("", self.dongche_btn)
        form_layout.addRow("", self.zhida_btn)

        # 组合布局
        layout.addLayout(form_layout)
        layout.addWidget(QLabel("推荐车次:"))
        layout.addWidget(self.recommend_list)
        layout.addWidget(self.start_btn)
        layout.addWidget(self.stop_btn)
        layout.addWidget(self.status_bar)

        self.setLayout(layout)

    def select_recommend(self, item):
        """处理推荐车次点击事件"""
        # 获取选中的车次信息
        selected_train = item.text()
        # 更新状态显示
        self.status_bar.showMessage(f"已选择监控车次：{selected_train}")
        # 可扩展逻辑：自动填充车次号到查询条件或触发预查询"

    def update_station_completer(self, stations):
        """更新车站自动补全数据（去重并优化匹配模式）"""
        # 去重并排序
        unique_stations = sorted(list(set(stations)))
        self.from_completer.setModel(QtCore.QStringListModel(unique_stations))
        self.to_completer.setModel(QtCore.QStringListModel(unique_stations))

    def update_recommendations(self, recommendations):
        """更新推荐车次列表（智能排序优化）"""
        # 智能排序逻辑：优先余票多、出发时间合适的车次
        sorted_recommendations = sorted(recommendations,
            key=lambda x: (-x.get('left_tickets', 0), x.get('depart_time', '00:00')))
        # 提取车次号列表
        train_numbers = [train['number'] for train in sorted_recommendations]
        
        self.recommend_list.clear()
        self.recommend_list.addItems(train_numbers)